<?

	// IMPORT USERS FROM ACTIVE DIRECTORY

	include("inc/config.inc.php");

	// MySQL database connection
    $conn = mysqli_connect($config[dbhost], $config[dbuser], $config[dbpass], $config[dbname]);
    $con = new mysqli($config[dbhost], $config[dbuser], $config[dbpass], $config[dbname]);
    if (mysqli_connect_errno())
            die("Failed to connect to MySQL");


	// Connect to LDAP and get userlist into array
	$ad = ldap_connect($config[domainController]);
	$bd = ldap_bind($ad,$config[domainUser],$config[domainPass]) or die("Couldn't bind to AD!");
	$result = ldap_search($ad, $config[domainOU], "(&(CN=*))");
	$entries = ldap_get_entries($ad, $result);

	// Query holidays userlist in SQL and fill array
	$result = mysqli_query($conn, "SELECT * FROM users");
	$sqlUsers = Array();
	while ($user = mysqli_fetch_array($result))
		array_push($sqlUsers, $user[user]);


	// Loop over AD users
	for ($i=0; $i < $entries["count"]; $i++)
	{
		// Loop over SQL users
		$match = false;
		for ($n=0; $n < count($sqlUsers); $n++)
		{
			if (strtolower($entries[$i]["samaccountname"][0]) == strtolower($sqlUsers[$n]))
				$match = true;
		}

		$user = strtolower($entries[$i]["samaccountname"][0]);
		$firstname = $entries[$i]["givenname"][0];
		$lastname = $entries[$i]["sn"][0];
		$email = $entries[$i]["mail"][0];

		if ($match)
		{
			echo "\nUpdating: $user";
			mysqli_query($conn, "UPDATE users SET firstname='$firstname', lastname='$lastname', email='$email' WHERE user='$user'");
		}
		else
		{
			echo "\nAdding new user: $user ($firstname $lastname - $email)";
			mysqli_query($conn, "INSERT INTO users SET user='$user', firstname='$firstname', lastname='$lastname', email='$email', prestaged=1");
		}
	}


    ldap_unbind($ad);

?>

